/**
 * IOC：控制反转，控制的是执行流程，反转是将控制权反转给框架
 * DI：依赖注入，控制的是对象间的依赖关系，注入是将依赖的对象注入到类中
 * DIP：依赖倒置原则，面向接口编程，而不是面向实现编程
 * 
 * 【关系】：IOC是一种设计模式，遵从依赖倒置原则（DIP）；依赖注入（DI）是实现IOC的一种具体方式。
 */


// 怎样实现自动new 的  依赖注入
export class SimpleContainer {
    constructor() {
        this.containerMap = new Map();
    }

    set(id, value) {
        this.containerMap.set(id, value);
    }

    get(id) {
        return this.containerMap.get(id);
    }

    has(id) {
        return this.containerMap.has(id);
    }

    remove(id) {
        if (this.containerMap.has(id)) {
            this.containerMap.delete(id);
        }
    }

    static getInstance() {
        if (!SimpleContainer._instance) {
            SimpleContainer._instance = new SimpleContainer();
        }
        return SimpleContainer._instance;
    }

    get container() {
        return SimpleContainer._instance;
    }
}

SimpleContainer._instance = null;




@Service('human')
export class Human { }

@Service('clothes')
export class Clothes { }

export class Test {
    @Inject()
    human;
}



export function Service(idOrSingleton, singleton) {
    return function(target) {
        let id;
        let singleton;
        const container = SimpleContainer.getInstance();
        
        // if (typeof idOrSingleton === 'string') {
        //     id = idOrSingleton;
        //     singleton = singleton || false;
        // } else if (typeof idOrSingleton === 'boolean') {
        //     id = target.name;
        //     singleton = idOrSingleton;
        // } else {
        //     id = target.name;
        //     singleton = false;
        // }

        // const singleInstance = singleton ? new target() : null;
        container.set(id, singleInstance || new target());
    };
}

export function Inject(value) {
    return function(target, propertyKey) {
        const id = value || propertyKey;
        const container = SimpleContainer.getInstance();
        const _dependency = container.get(id) ? container.get(id) : null;
        if (_dependency) {
            target[propertyKey] = _dependency;
        }
        return target;
    };
}



// https://juejin.cn/post/7079612337111924772
// https://juejin.cn/post/6920850842375421959?from=search-suggest【重要】
// https://juejin.cn/post/7260756459671044153
// https://cloud.tencent.com/developer/article/2078975
// https://blog.csdn.net/gitblog_01138/article/details/151493662